/**
 * 
 */
package br.com.lazyprogrammer.worldsoccermanager.fragments.main;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import br.com.lazyprogrammer.worldsoccermanager.HomeActivity;
import br.com.lazyprogrammer.worldsoccermanager.MainActivity;
import br.com.lazyprogrammer.worldsoccermanager.R;
import br.com.lazyprogrammer.worldsoccermanager.network.interfaces.TeamListener;
import br.com.lazyprogrammer.worldsoccermanager.network.model.Team;
import br.com.lazyprogrammer.worldsoccermanager.network.model.User;
import br.com.lazyprogrammer.worldsoccermanager.network.model.dao.TeamDAO;
import br.com.lazyprogrammer.worldsoccermanager.network.model.dao.UserDAO;
import br.com.lazyprogrammer.worldsoccermanager.network.Request;
import br.com.lazyprogrammer.worldsoccermanager.network.interfaces.LoginListener;
import br.com.lazyprogrammer.worldsoccermanager.network.task.GetTeamTask;
import br.com.lazyprogrammer.worldsoccermanager.network.task.LoginTask;
import br.com.lazyprogrammer.worldsoccermanager.preferences.interfaces.ActionPreferences;
import br.com.lazyprogrammer.worldsoccermanager.preferences.interfaces.OnPreferencesChangedListener;
import br.com.lazyprogrammer.worldsoccermanager.system.generator.Generator;
import br.com.lazyprogrammer.worldsoccermanager.system.keyboard.Keyboard;
import br.com.lazyprogrammer.worldsoccermanager.system.message.Message;
import br.com.lazyprogrammer.worldsoccermanager.util.PoolData;

/**
 * 
 * @author Limao Games <br />
 * <b>Email:</b> andreikeda@limaogames.com.br <br />
 * created on: 13/01/2014
 * @version 1.0
 * @see 
 */
public class LoginFragment extends Fragment implements OnClickListener, Request.Callback, LoginListener,
        DialogInterface.OnCancelListener {

    private TeamDAO teamDAO = new TeamDAO();
	private UserDAO userDAO	= new UserDAO();

    private TeamListener listener;
	
	private Button buttonLogin;
	private EditText inputPassword, inputUsername;
	private LinearLayout layoutLoginLoading;
    private ProgressDialog pgLoading;
	private TextView labelForgotPassword, labelNotRegistered;


	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionCancel(java.lang.Class)
	 */
	@Override
	public void onCancel(Class<?> executingClass) {
		if (executingClass.equals(LoginTask.class))
			layoutLoginLoading.setVisibility(View.GONE);
        if (executingClass.equals(GetTeamTask.class))
            hideLoading();
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionError(java.lang.Class, java.lang.String)
	 */
	@Override
	public void onError(Class<?> executingClass, Request.Response response, String errorMessage) {
		if (executingClass.equals(LoginTask.class)) {
			layoutLoginLoading.setVisibility(View.GONE);
		}
        if (executingClass.equals(GetTeamTask.class)) {
            hideLoading();
            ((MainActivity) getActivity()).goToHomeScreen();
        }

        Message.send(getActivity(), errorMessage);
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionStart(java.lang.Class)
	 */
	@Override
	public void onStart(Class<?> executingClass) {
		if (executingClass.equals(LoginTask.class))
			layoutLoginLoading.setVisibility(View.VISIBLE);
        else if (executingClass.equals(GetTeamTask.class))
            showLoading(false, getResources().getString(R.string.loading_get_team));
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionSuccess(java.lang.Object, java.lang.Class)
	 */
	@Override
	public void onSuccess(Class<?> executingClass, Object result) {
		if (executingClass.equals(LoginTask.class)) {
			layoutLoginLoading.setVisibility(View.GONE);
			if (PoolData.user.isActive()) {
                if (!teamDAO.isGetTeamTaskRunning())
                    teamDAO.get(getActivity(), this, listener, PoolData.user.getId());
            }
			else
				((MainActivity) getActivity()).goToConfirmAccountScreen();
		}
        if (executingClass.equals(GetTeamTask.class)) {
            hideLoading();
            ((MainActivity) getActivity()).goToHomeScreen();
        }
    }
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		//mPref	= WSMApplication.getInstance().getPreferences();
		//getPref	= WSMApplication.getInstance().getPreferences();
        listener = new TeamListener() {
            @Override
            public void onTeamCreated(Team team) {

            }

            @Override
            public void onTeamLoaded(Team team) {
                PoolData.team = team;
            }
        };
	}

    @Override
    public void onCancel(DialogInterface dialogInterface) {

    }
	
	@Override
	public void onClick(View v) {
		Keyboard.close(getActivity(), inputUsername);
		if (v.equals(buttonLogin))
			login(getUsernameInputText(), getPasswordInputText());/*
		else if (v.equals(labelNotRegistered))
			((MainActivity) getActivity()).goToRegisterAccount();*/
		else if (v.equals(labelForgotPassword))
			((MainActivity) getActivity()).goToForgotPasswordScreen();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_login, container, false);
		
		setViews(view);
		setListeners();
		updateUI();
		
		return view;
	}
	
	@Override
	public void onResume() {
		super.onResume();

		/*if (WSMApplication.getInstance().getUser() != null)
			((MainActivity) getActivity()).goToHome();
		else if (getPref.isUserLogged())
			login(getPref.getUsername(), getPref.getPassword());*/
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.games.sports.managersoccer.network.interfaces.LoginListener#onLoginSuccessful(br.com.limaogames.games.sports.managersoccer.model.User)
	 */
	@Override
	public void onLoginSuccessful(User user, String password) {
		// TODO Auto-generated method stub
		PoolData.mPref.onPasswordChanged(password);
        PoolData.mPref.onUsernameChanged(user.getUsername());
        PoolData.mPref.onUserIdChanged(user.getId());

        PoolData.user = user;
		//WSMApplication.getInstance().setUser(user);
	}


	public void setViews(View view) {
		buttonLogin		= (Button) view.findViewById(R.id.button_login);
		
		inputPassword	= (EditText) view.findViewById(R.id.input_password);
		inputUsername	= (EditText) view.findViewById(R.id.input_email);
		
		labelForgotPassword	= (TextView) view.findViewById(R.id.label_forgot_password);
		labelNotRegistered	= (TextView) view.findViewById(R.id.label_not_registered);
		
		layoutLoginLoading		= (LinearLayout) view.findViewById(R.id.layout_loading);
	}

	public void setListeners() {
		buttonLogin.setOnClickListener(this);
		
		labelForgotPassword.setOnClickListener(this);
		labelNotRegistered.setOnClickListener(this);
	}

	public void updateUI() {
		// TODO Auto-generated method stub
		labelForgotPassword.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		labelNotRegistered.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		
		inputPassword.setTypeface(null, Typeface.NORMAL);
		inputPassword.setTransformationMethod(new PasswordTransformationMethod());
	}
	
	private String getPasswordInputText() {
		return Generator.encodePassword(inputPassword.getText().toString().trim(), getResources().getConfiguration().locale);
	}
	
	private String getUsernameInputText() {
		return inputUsername.getText().toString();
	}

    private void hideLoading() {
        if (pgLoading != null)
            pgLoading.dismiss();
    }

    private void login(String username, String password) {
		if (!username.equals("") && !password.equals("")) {
			if (!userDAO.isLoginTaskRunning()) {
				Keyboard.close(getActivity(), inputUsername);
				userDAO.login(getActivity(), this, this, username, password);
			}
		}
		else
			Message.send(getActivity(), R.string.exception_empty_field);
	}

    private void showLoading(boolean cancelable, String message) {
        if (pgLoading == null) {
            pgLoading = new ProgressDialog(getActivity());
            pgLoading.setTitle(R.string.loading);
        }
        pgLoading.setMessage(message);
        pgLoading.setCancelable(cancelable);
        if (cancelable)
            pgLoading.setOnCancelListener(this);
        pgLoading.show();
    }
}
